<template>
	<view class="customer-container">
		<el-card class="page">
			<div slot="header" class="clearfix">
				<span>房屋管理</span>

				<el-button style="float: right;" type="primary" size="small" @click="downloadFile">下载模板</el-button>
				<el-upload style="float: right; margin-right: 10px;" class="upload-demo" action="" :auto-upload="false"
					:on-change="handleFileChange" accept=".xlsx,.xls" :show-file-list="false">
					<el-button type="info" size="small" >导入</el-button>
				</el-upload>
			</div>
			<el-form :inline="true" label-width="80px" size="mini" class="search-form">
				<el-form-item label="楼栋" prop="buildingNumber" clearable>
					<el-input v-model="buildingNumber"  placeholder="请输入电话或者名称"></el-input>
				</el-form-item>
				<el-form-item label="楼层" prop="consultantId">
					<el-input v-model="floor"  placeholder="请输入电话或者名称"></el-input>
				</el-form-item>
				<el-form-item label="房号" prop="roomNumber">
					<el-input v-model="roomNumber"  placeholder="请输入电话或者名称"></el-input>
				</el-form-item>
				<el-form-item label="户型" prop="roomLayout">
					<el-select v-model="roomLayout" clearable>
						<el-option v-for="item in houseTypeList" :value="item.value" :label="item.text"
							v>{{item.text}}</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select v-model="status" clearable>
						<el-option v-for="item in statusList" :value="item.value" :label="item.text"
							>{{item.text}}</el-option>
					</el-select>
				</el-form-item>
			<!-- 	<el-form-item label="创建时间" prop="createTime">
					<el-date-picker v-model="createTime" type="daterange" range-separator="至" start-placeholder="开始日期"
						:default-time="['00:00:00', '23:59:59']" end-placeholder="结束日期"
						value-format="yyyy-MM-dd HH:mm:ss" align="right"></el-date-picker>
				</el-form-item> -->
				<el-form-item>
					<el-button type="primary" @click="onSeach">查询</el-button>
				</el-form-item>
			</el-form>
			<div class="table-container">
				<el-table :data="customers" style="width: 100%;" :height="tableHeight" border size="small" align="center">
					<el-table-column prop="buildingNumber" label="楼栋" width="60" align="center"></el-table-column>
					<el-table-column prop="floor" label="楼层" width="60"></el-table-column>
					<el-table-column prop="houseText" label="房号" width="110" align="center"></el-table-column>
					<el-table-column prop="roomLayout" label="户型" sortable width="100"align="center"></el-table-column>
					<el-table-column prop="area" label="面积" width="100" align="center">
					</el-table-column>
					<el-table-column prop="houseType" label="户型F" width="60" align="center">
					</el-table-column>
					<el-table-column prop="usableArea" label="套内" width="60" align="center">
					</el-table-column>
					<el-table-column prop="publicPercent" label="公摊系数%" width="90" align="center">
						<template slot="default" slot-scope="scope">
							
							{{scope.row.publicPercent?scope.row.publicPercent.toFixed(2):''}}
							<!-- <el-tag  :class="getHouseStatusClass(scope.row)" size="mini">
								{{ getStatusText(scope.row.status) }}
							</el-tag> -->
						</template>
					</el-table-column>
					<el-table-column prop="publicArea" label="分摊面积" width="80" align="center">
						<template slot="default" slot-scope="scope">
							{{scope.row.publicArea?scope.row.publicArea.toFixed(2):''}}
							<!-- <el-tag  :class="getHouseStatusClass(scope.row)" size="mini">
								{{ getStatusText(scope.row.status) }}
							</el-tag> -->
						</template>
					</el-table-column>
					<el-table-column prop="price" label="单价" width="100">
					</el-table-column>
					<el-table-column prop="totalPrice" label="总价" width="100">
					</el-table-column>
					<el-table-column prop="minPrice" label="最低价" width="100">
					</el-table-column>
					<el-table-column prop="status" width="80" align="center" label="状态">
						<template slot="default" slot-scope="scope">
							<el-tag  :class="getHouseStatusClass(scope.row)" size="mini">
								{{ getStatusText(scope.row.status) }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="remark" show-overflow-tooltip label="备注"></el-table-column>
				</el-table>
			</div>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNo"
				:page-sizes="[10,20,50,100]" :page-size="pageSize" background
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</el-card>

		<!-- Excel导入对话框 -->
		<el-dialog title="导入客户" :visible.sync="importDialogVisible" width="90%" size="small">
			<div v-if="excelData.length > 0" style="margin-top: 20px;">
				<el-table :data="excelData" height="300" border>
					<el-table-column v-for="(item, index) in excelHeaders" :show-overflow-tooltip="true" :key="index"
						:prop="item.prop" :label="item.label" width="120"></el-table-column>
					<el-table-column label="操作" width="150" fixed="right">
						<template slot-scope="scope">
							<!-- <el-button @click="editExcelRow(scope.row, scope.$index)" type="text" size="small">编辑</el-button> -->
							<el-button @click="deleteExcelRow(scope.$index)" type="text" size="small">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<span slot="footer" class="dialog-footer">
				<el-button @click="importDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="importCustomers" :loading="exportLoading" :disabled="excelData.length === 0">导 入</el-button>
			</span>
		</el-dialog>
	</view>
</template>

<script>
	// 引入xlsx插件
	import * as XLSX from 'xlsx';

	export default {
		data() {
			return {
				customers: [],
				dialogVisible: false,
				importDialogVisible: false,
				floor:'',
				buildingNumber:'',
				houseText:'',
				roomLayout:'',
				roomNumber:'',
				createTime: [],
				dialogTitle: '新增客户',
				excelFile: null,
				excelData: [],
				excelHeaders: [],
				total: 0,
				pageNo: 1,
				pageSize: 10,
				conUserList: [],
				keyword: '',
				status: '',
				houseTypeList:[{
							text: '两室一卫',
							value: '两室一卫',
						},
						{
							text: '三室两卫',
							value: '三室两卫'
				},{
							text: '四室两卫',
							value: '四室两卫'
				}],
				statusList: [{
						text: '可售',
						value: 1,
						class: 'status-1'
					},
					{
						text: '认购',
						class: 'status-2',
						value: 2
					},
					{
						text: '签约',
						class: 'status-3',
						value: 3
					},
					{
						text: '销控',
						class: 'status-3',
						value: 4
					}

				],
				tableHeight: '500px',
				exportLoading:false
			}
		},
		created() {
			this.getConlists()
		},
		mounted() {
			// 页面加载时获取客户列表
			this.loadData();
			this.$nextTick(() => {
				setTimeout(()=>{
					this.calculateTableHeight();
				},1000)
			});

			// 监听窗口大小变化
			window.addEventListener('resize', this.calculateTableHeight);
		},
		beforeDestroy() {
			// 移除监听
			window.removeEventListener('resize', this.calculateTableHeight);
		},
		methods: {
			downloadFile(){
				window.location.href = 'https://mp-452d196f-0ddc-4f53-aafa-efaac69b4962.cdn.bspapp.com/template/house_template.xlsx'
			},
			calculateTableHeight() {
				this.$nextTick(() => {
					const container = document.querySelector('.customer-container');
					if (!container) return;

					// 获取页面头部高度
					const headerHeight = container.querySelector('.el-card__header')?.offsetHeight || 0;

					// 获取搜索表单高度
					const searchFormHeight = container.querySelector('.search-form')?.offsetHeight || 0;

					// 获取分页高度
					const paginationHeight = container.querySelector('.pagination-container')?.offsetHeight ||
						64; // 默认 64px

					// 获取容器总高度
					const containerHeight = container.offsetHeight;

					// 计算表格可用高度
					// 总高度 - 头部 - 搜索表单 - 分页 - 内边距和边距
					const paddingMargin = 40; // 预估的内边距和边距
					const calculatedHeight = containerHeight - headerHeight - searchFormHeight - paginationHeight -
						paddingMargin;
					
					console.log('headerHeight',containerHeight,headerHeight,searchFormHeight)
					
					// 设置最小高度
					this.tableHeight = Math.max(calculatedHeight, 200);
				});
			},
			getConlists() {
				this.$cloudOBjAjax('sunny-users', 'getConsultantList', {}).then(res => {
					this.conUserList = res
				})
			},
			onSeach() {
				this.pageNo = 1
				this.loadData()
			},
			addCustomer() {
				this.dialogTitle = '新增客户';
				this.currentCustomer = {
					id: 0,
					name: '',
					phone: '',
					email: ''
				};
				this.dialogVisible = true;
			},
			editCustomer(row) {
				this.dialogTitle = '编辑客户';
				this.currentCustomer = {
					...row
				};
				this.dialogVisible = true;
			},
			deleteCustomer(row) {
				this.$confirm('此操作将永久删除该客户, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.customers = this.customers.filter(customer => customer.id !== row.id);
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			handleSizeChange(val) {
				this.pageSize = val
				this.loadData()
			},
			handleCurrentChange(val) {
				this.pageNo = val
				this.loadData()
			},
			// 加载客户列表
			loadData() {
				this.$cloudOBjAjax('sunny-house', 'queryHouseList', {
					buildingNumber:this.buildingNumber,
					floor:this.floor,
					roomLayout:this.roomLayout,
					pageNo: this.pageNo,
					pageSize: this.pageSize,
					roomNumber:this.roomNumber,
					status: this.status,
				}).then(res => {
					this.customers = res.list
					this.total = res.total
				})
			},
			// 处理文件选择变化
			handleFileChange(file) {
				this.excelFile = file.raw;
				this.parseExcel();
			},
			getHouseStatusClass(house) {
				let statusClass = {
					1: 'available', // 可售
					2: 'reserved', // 已预订
					3: 'sold',
					4:'disabled'// 已售
				} [house.status] || 'available';
			
				return statusClass;
			},
			
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					1: '可售',
					2: '认购',
					3: '签约',
					4:'销控'
				};
				return statusMap[status] || '未知';
			},
		
			// 解析Excel文件
			parseExcel() {
				if (!this.excelFile) return;

				const reader = new FileReader();
				reader.onload = (e) => {
					try {
						const data = new Uint8Array(e.target.result);
						const workbook = XLSX.read(data, {
							type: 'array'
						});
						
						console.log('workbook',workbook.SheetNames)
						// 获取第一个工作表
						const firstSheetName = workbook.SheetNames[0];
						const worksheet = workbook.Sheets[firstSheetName];
						
						console.log('worksheet',worksheet)
						
						// 将工作表转换为JSON数据
						const jsonData = XLSX.utils.sheet_to_json(worksheet);
						
						console.log('headerss',jsonData)
					

						const headers = jsonData[0]
						// 处理表头
						if (jsonData.length > 0) {
							this.excelHeaders = Object.keys(headers).map(key => ({
								prop: key,
								label: headers[key]
							}));
						}
						console.log('headers[0]',headers[0])
						if(this.excelHeaders[0].prop!="sunny_house_build"){
							return this.$message({
								type:'error',
								message:'模板不对'
							})
						}
						
						this.excelData = jsonData.filter((item, index) => {return index>1})

						this.importDialogVisible = true
					} catch (error) {
						this.$message({
							type: 'error',
							message: '解析Excel文件失败: ' + error.message
						});
					}
				};
				reader.readAsArrayBuffer(this.excelFile);
			},
			convertExcelNumberToDate(num) {
				if (typeof num !== 'number') return num;

				// Excel 日期从 1899-12-30 开始
				const date = new Date((num - 25569) * 86400 * 1000);

				// 调整时区（如果需要）
				const tzOffset = date.getTimezoneOffset() * 60000;
				const adjustedDate = new Date(date.getTime() + tzOffset);

				const year = adjustedDate.getFullYear();
				const month = String(adjustedDate.getMonth() + 1).padStart(2, '0');
				const day = String(adjustedDate.getDate()).padStart(2, '0');

				return `${year}/${month}/${day}`;
			},
			convertRooms(str) {
			  // 定义汉字数字映射
			  const numMap = {
			    '一': 1, '两': 2, '二': 2, '三': 3, '四': 4,
			    '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10
			  };
			  
			  // 使用正则表达式匹配 "数字+室" 和 "数字+卫"
			  const roomMatch = str.match(/([一二三四五六七八九十两]+)室/);
			  const bathMatch = str.match(/([一二三四五六七八九十两]+)卫/);
			  
			  // 提取并转换数字
			  const rooms = roomMatch ? (numMap[roomMatch[1]] || parseInt(roomMatch[1], 10) || 0) : 0;
			  const bathrooms = bathMatch ? (numMap[bathMatch[1]] || parseInt(bathMatch[1], 10) || 0) : 0;
			  
			  return  {
				  rooms,
				  bathrooms
			  }
			},
			// 导入客户数据
			importCustomers() {
				if (this.excelData.length === 0) {
					this.$message({
						type: 'warning',
						message: '没有数据可以导入'
					});
					return;
				}
				
				this.exportLoading = true
				// 映射字段
				const mappedData = this.excelData.map(item => {
					// 对所有字段进行去空格处理
					const trimmedItem = {};
					for (const key in item) {
						trimmedItem[key] = typeof item[key] === 'string' ? item[key].trim() : item[key];
					}

					const roomObj = this.convertRooms(item.__EMPTY_3)
					return {
						buildingNumber:item.sunny_house_build,
						floor: Number(item.__EMPTY),
						roomNumber:Number(item.__EMPTY_1),
						status:1,
						area:item.__EMPTY_4,
						usableArea:item.__EMPTY_5,
						publicArea:item.__EMPTY_7,
						publicPercent:item.__EMPTY_6*100,
						livingRoomCount:2,
						roomCount:roomObj.rooms,
						bathroomCount:roomObj.bathrooms,
						roomLayout:item.__EMPTY_3,
						houseType:item.__EMPTY_8,
						houseText:item.__EMPTY_2,
						priceUnit:item.__EMPTY_9,
						totalPrice:item.__EMPTY_10,
						realPrice:item.__EMPTY_11,
						remark:item.__EMPTY_12,
						roomNumberLayout:`${Number(item.__EMPTY)>10?Number(item.__EMPTY):'0'+Number(item.__EMPTY)}${Number(item.__EMPTY_1)>10?Number(item.__EMPTY_1):'0'+Number(item.__EMPTY_1)}`
					};
				});

				// 这里应该调用云函数导入数据

				this.$cloudOBjAjax('sunny-house', 'importByExcel', {
					list: mappedData
				}).then(res => {
					console.log(res)
					this.exportLoading = false
					this.$message({
						type: 'success',
						message: `成功读取${mappedData.length}条数据，实际导入${res.successCount}条,已存在${res.duplicateCount}条`
					});
					this.importDialogVisible = false;
					this.excelData = [];
					this.excelHeaders = [];
				}).catch(err => {
					this.exportLoading = false
					console.log(err)
					this.$message({
						type: 'error',
						message: err.errMsg
					})
				})

			},
			// 编辑Excel行数据
			editExcelRow(row, index) {
				// 这里可以添加编辑逻辑，比如打开一个对话框编辑行数据
				this.$message({
					type: 'info',
					message: '编辑功能待实现，可以选择在弹窗中编辑第' + (index + 1) + '行数据'
				});
			},
			// 删除Excel行数据
			deleteExcelRow(index) {
				this.$confirm('确定要删除这条数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.excelData.splice(index, 1);
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	.customer-container {
		flex: 1;
		height: 100%;
		padding: 20px;
		box-sizing: border-box;

	}

	::v-deep .page {
		height: 100%;
	}

	.customer-status-tag {
		padding: 2px 8px;
		border-radius: 6px;
		font-size: 12px;
		font-weight: 500;

		/* 不同状态的样式 */
		&.status-1 {
			background: #e6f7ff;
			color: #1890ff;
			border: 1px solid #91d5ff;
		}

		&.status-2 {
			background: #f6ffed;
			color: #52c41a;
			border: 1px solid #b7eb8f;
		}

		&.status-3 {
			background-color: #fff7e6;
			color: #fa8c16;
			border: 1px solid #ffd591;
		}

		&.status-41 {
			background: #fff2f0;
			color: #ff4d4f;
			border: 1px solid #ffccc7;
		}

		&.status-14 {
			background: #f9f0ff;
			color: #722ed1;
			border: 1px solid #d3adf7;
		}

		&.status-15 {
			background: #f6ffed;
			color: #52c41a;
			border: 1px solid #b7eb8f;
		}

		&.status-unknown {
			background: #fafafa;
			color: #8c8c8c;
			border: 1px solid #d9d9d9;
		}
	}

	::v-deep .btn-prev {
		height: 28px;
		line-height: 26px;
	}

	::v-deep .btn-next {
		height: 28px;
		line-height: 26px;
		border-color: #999;
	}
</style>